﻿using aier.business.logic;
using aier.wx.nosql.redis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;


namespace aier.wx.api.selfhost.Controllers
{
    /// <summary>
    ///  微信小程序登录
    /// </summary>
    [RoutePrefix("api/MPWXLogin")]
    public class MPWXLoginController : ApiController
    {
        private string APPID = "wx7847a33345a04c52";
        private string SECRET = "b0e0e375b6a44e807fbd5b1a959056a1";

        public RedisTestDal redisTestDal { get; set; }

        public SequenceBll sequenceBll { get; set; }

        /// <summary>
        /// 微信小程序使用微信号等录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="mPWXUserBO"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("{code}")]
        public async Task<IHttpActionResult> Post([FromUri]string code, [FromBody]MPWXUserBO mPWXUserBO)
        {
            HttpClient httpClient = new HttpClient()
            {
                BaseAddress = new Uri("https://api.weixin.qq.com")
            };
            string path = $"/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={code}&grant_type=authorization_code";
            var response = await httpClient.GetAsync(path);
            var data = await response.Content.ReadAsStringAsync();
            dynamic jsonData = JsonConvert.DeserializeObject<ExpandoObject>(data);

            var dics = jsonData as IDictionary<string, Object>;
            if (!object.ReferenceEquals(null, jsonData) && dics.Keys.Contains("openid"))
            {
                mPWXUserBO.mpWxOpenId = jsonData.openid;
                mPWXUserBO.sessionKey = jsonData.session_key;

            }

            RespMsg<MPWXUserBO> respMsg = new RespMsg<MPWXUserBO>();

            if (redisTestDal.Get<MPWXUserBO>(mPWXUserBO.mpWxOpenId) != null)
            {
                mPWXUserBO = redisTestDal.Get<MPWXUserBO>(mPWXUserBO.mpWxOpenId);
            }
            else
            {
                mPWXUserBO.id = sequenceBll.GetSCNum();
                mPWXUserBO.userUniqueToken = Guid.NewGuid().ToString();
                mPWXUserBO.registTime = DateTime.Now;
                redisTestDal.Set<MPWXUserBO>(mPWXUserBO.mpWxOpenId, mPWXUserBO, TimeSpan.FromMinutes(60));
            }


            respMsg.data = mPWXUserBO;
            respMsg.status = (int)HttpStatusCode.OK;


            return Ok(respMsg);
        }
    }

    public class MPWXUserBO
    {
        public string id { get; set; }

        public string sessionKey { get; set; }

        public string avatarUrl { get; set; }

        public string nickName { get; set; }

        public int whichMP { get; set; }

        public string mpWxOpenId { get; set; }

        public string userUniqueToken { get; set; }

        public DateTime registTime { get; set; }
    }

    public class RespMsg<T>
    {
        public T data { get; set; }
        public int status { get; set; }
    }

}
